#include "codeeditor.h"

// CodeEditor::CodeEditor() {}

CodeEditor::CodeEditor(QWidget *parent)
    : QPlainTextEdit(parent)
    , keywords{"for", "while", "if", "else", "def", "return", "import", "class", "int", "long long"}
{
    // 创建QCompleter并设置关键词
    completer = new QCompleter(this);
    completer->setModel(new QStringListModel(keywords, completer));
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    completer->setWidget(this);

    QFont font = completer->popup()->font();
    font.setPointSize(12); // 设置字体大小为 12
    completer->popup()->setFont(font);
    completer->popup()->setMinimumWidth(150);  // 设置最小宽度

    // 当补全项被激活时，插入补全内容
    connect(completer, QOverload<const QString&>::of(&QCompleter::activated), this, &CodeEditor::insertCompletion);
}

void CodeEditor::keyPressEvent(QKeyEvent *event)
{
    // 判断是否需要处理补全
    if (completer && completer->popup()->isVisible()) {
        // 处理Tab、Return、Esc和其他键
        switch (event->key()) {
        case Qt::Key_Tab:
        case Qt::Key_Return:
        case Qt::Key_Enter:
        case Qt::Key_Escape:
            event->ignore();
            return; // 忽略这些按键
        default:
            break;
        }
    }

    // 调用基类的按键处理
    QPlainTextEdit::keyPressEvent(event);

    QString completionPrefix = getCompletionPrefix();

    if (completionPrefix.isEmpty() || keywords.contains(completionPrefix)){
        completer->popup()->hide();
        return;
    }



    if (completionPrefix != completer->completionPrefix()) {
        completer->setCompletionPrefix(completionPrefix);
        completer->popup()->setCurrentIndex(completer->completionModel()->index(0, 0));
    }

    // 设置补全框的位置
    QRect cr = cursorRect();
    cr.setWidth(completer->popup()->sizeHintForColumn(0) +
                completer->popup()->verticalScrollBar()->sizeHint().width());
    completer->complete(cr); // 在光标处展示补全
}

void CodeEditor::insertCompletion(const QString &completion)
{
    QTextCursor tc = textCursor();
    tc.select(QTextCursor::WordUnderCursor);
    tc.insertText(completion);
    setTextCursor(tc);
}

QString CodeEditor::getCompletionPrefix()
{
    QTextCursor tc = textCursor();
    tc.select(QTextCursor::WordUnderCursor);
    return tc.selectedText();
}
